/** @file    DataBaseManager.cpp
 *  @author  Alessandro Polo
 *  @version $Id: DataBaseManager.cpp 2142 2010-03-16 12:45:50Z alex $
 *  @brief
 * File containing methods for the wosh::DataBaseManager class.
 * The header for this class can be found in DataBaseManager.h, check that file
 * for class description.
 ****************************************************************************/
/* Copyright (c) 2007-2010, WOSH - Wide Open Smart Home 
 * by Alessandro Polo - OpenSmartHome.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or materials provided with the distribution.
 *     * Neither the name of the OpenSmartHome.com WOSH nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Alessandro Polo ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Alessandro Polo BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ****************************************************************************/

 #include <core/DataBaseManager.h>

 #include <core/ObjectFactory.h>
 #include <core/WoshKernel.h>
 #include <core/SystemError.h>
 #include <core/Fact.h>
 #include <core/MethodsDef.h>
 #include <core/NEW_List.h>
 #include <core/Table.h>
 #include <core/Utilities.h>


using namespace std;
namespace wosh {

 WOSH_REGISTER_INTERFACE(wosh::DataBase, "wosh::Object", 0.01, _static_DataBase)


// Gamma singleton! static reference is allocated and maintained by WoshKernel
extern "C" {
	DataBaseManager* DataBaseManager::getInstance() { 
		if ( WoshKernel::getInstance() == NULL ) return NULL;
		return &WoshKernel::getInstance()->database();
	}
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////// CONSTRUCTORS

DataBaseManager::DataBaseManager( const WoshKernel* parent ) : WoshModule(parent)
 {
	Object::setName( _DataBaseManager_NAME );
	Object::getURI().fromString( _DataBaseManager_URI );
	Object::getURI().registerGlobal();

//Log.setLevel( VERBOSE );

	Log(LOG_VERBOSE, " Initializing.." );
	Properties.set( _DataBaseManager_KEY_DataBase_Count, 0, Permission(Permission::Read) );

	Log(LOG_VERBOSE, " Registering Methods.." );
	MethodRequest* mmList = Methods.create<MethodRequest>( _METHOD_List, "List installed protocols", Permission(Permission::RX) );
	mmList->setMethod( this, (MethodRequestPtr)&DataBaseManager::mmDoList );

	MethodRequest* mmListSupportedProtocols = Methods.create<MethodRequest>( _DataBaseManager_METHOD_ListSupportedProtocols, "List installed protocols", Permission(Permission::RX) );
	mmListSupportedProtocols->setMethod( this, (MethodRequestPtr)&DataBaseManager::mmDoListSupportedProtocols );


 }

DataBaseManager::~DataBaseManager()
 {
	Log(LOG_INFO, " Destroying.." );

	this->dbs.free();

	Log(LOG_VERBOSE, ":~DataBaseManager() Destroyed." );
 }

//////////////////////////////////////////////////////////////////////////////////////////////// CONSTRUCTORS
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////// KERNEL EVENTS

WRESULT DataBaseManager::onKernelInitializing() {
	WRESULT ret = WoshModule::onKernelInitializing();

	if ( Properties.exists(_DataBaseManager_KEY_AutoLoadProtocols) ) {
		vector<string> protos;
		string protoStr = Properties.getValueOf(_DataBaseManager_KEY_AutoLoadProtocols).toString();
		Utilities::splitString(protoStr, ";", protos, false, true);
		WRESULT ret_c = WRET_OK;

		std::vector<std::string>::iterator it;
		for ( it=protos.begin(); it!=protos.end(); ++it ) {
			DataBase* db_proto = loadDataBase(*it);
			if ( db_proto == NULL ) {
				ret += WRET_ERR_PARAM;
				continue;
			 }
			ret_c = installDataBase(db_proto);
			ret += ret_c;
		 }

	 }

	return ret;
 }

/////////////////////////////////////////////////////////////////////////////////////////////// KERNEL EVENTS
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////// DATABASE METHODS

WRESULT DataBaseManager::installDataBase( DataBase* db_implementation ) {
	if ( db_implementation == NULL ) return WRET_ERR_PARAM;
	if ( db_implementation->getProtocol() == "" ) return WRET_ERR_PARAM;
	Log(LOG_INFO, ":installDataBase(%s) : Registering DataBase..",  db_implementation->getProtocol().c_str() );

	this->dbs.transactionBeginWrite();
	if ( this->dbs.exists(db_implementation->getProtocol()) ) {
		this->dbs.transactionEnd();
		SystemError::raise(this, Log, SystemError::CRITICAL, 0, "installDataBase()", "FAILED Registering %s", db_implementation->getProtocol().c_str() );
		return WRET_ERR_PARAM;
	 }

	db_implementation->getURI().clear();
	db_implementation->getURI().setParent( this->getURI() );
	db_implementation->getURI().setName( db_implementation->getName() );
	db_implementation->getURI().registerGlobal();

	this->dbs.set(db_implementation->getProtocol(), db_implementation);
	Properties.update( _DataBaseManager_KEY_DataBase_Count, this->dbs.size() );
	this->dbs.transactionEnd();

	Fact* fact = new Fact( _DataBaseManager_EVENT_DatabaseInstalled, new Variant(db_implementation->getProtocol()));
	Message* msg_event = new Message();
	msg_event->setSource( this );
	msg_event->setContent( fact );
	msg_event->getDestination().setAny();
	msg_event->getDestination().setKernelLocal();
	BusCore.postMessage(msg_event);
	return WRET_OK;
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

WRESULT DataBaseManager::unRegisterDataBase( DataBase* db_implementation ) {
	if ( db_implementation == NULL ) return WRET_ERR_PARAM;
	if ( db_implementation->getProtocol() == "" ) return WRET_ERR_PARAM;

	this->dbs.transactionBeginWrite();
	if ( this->dbs.exists(db_implementation->getProtocol()) ) {
		this->dbs.transactionEnd();
		SystemError::raise(this, Log, SystemError::CRITICAL, 0, "unRegisterDataBase()", "FAILED UnRegistering %s", db_implementation->getProtocol().c_str() );
		return WRET_ERR_PARAM;
	 }
	this->dbs.remove(db_implementation->getProtocol(), true);
	this->dbs.transactionEnd();

	Log(LOG_INFO, ":unRegisterDataBase() unRegistered '%s'",  db_implementation->getProtocol().c_str() );
	return WRET_OK;
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

DataBase* DataBaseManager::loadDataBase( const string& database_name ) {
	Log(LOG_VERBOSE, ":loadDataBase(%s) : Requesting ObjectFactory to allocate..", database_name.c_str() );

	DataBase* database = ObjectFactory::createTypeOf<DataBase>(database_name, 0.0);
	//database->setPermission( Permission(username, group, Permission::RWX, Permission::RX, Permission::Read) );
	if ( database == NULL ) {
		SystemError::raise(this, Log, SystemError::CRITICAL, 0, "loadDataBase", "FAILED (NULL) creating DataBase %s!", database_name.c_str() );
		return NULL;
	 }

//	SystemError::raise(this, Log, SystemError::CRITICAL, 0, "loadDataBase", "DataBase %s NOT found!", database_name.c_str() );
	return database;
 }

//////////////////////////////////////////////////////////////////////////////////////////// DATABASE METHODS
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

Response* DataBaseManager::mmDoList( const Request* request ) {
	if ( request == NULL ) return NULL;
	string option = request->getArgument().toString();
	Log(LOG_VERBOSE, ":mmDoList(%s)", option.c_str() );

	if ( option == "s" || option == "short" ) {
		this->dbs.transactionBeginRead();
		NEW_List* objs = new NEW_List(this->dbs.size());
		tStrDataBaseMap::ConstIterator it;
		const tStrDataBaseMap::ConstIterator it_end = this->dbs.end();
		for ( it=this->dbs.begin(); it!=it_end; ++it ) {
			if ( it->second == NULL ) continue;
			objs->push_back<Variant>( it->first );
		}
		this->dbs.transactionEnd();
		return request->replyResponse(WRET_OK, objs);
	 }
	else {
		this->dbs.transactionBeginRead();
		Table* tbl = new Table( this->dbs.size(), 4, true );
		tbl->setTableName("DataBases");
		tbl->setHeaderHorizontal("Name", 0);
		tbl->setHeaderHorizontal("Protocol", 1);
		tbl->setHeaderHorizontal("Type", 2);
		tbl->setHeaderHorizontal("URI", 3);
		unsigned int iRow = 0;
		tStrDataBaseMap::ConstIterator it;
		const tStrDataBaseMap::ConstIterator it_end = this->dbs.end();
		for ( it=this->dbs.begin(); it!=it_end; ++it, ++iRow ) {
			if ( it->second == NULL ) continue;
			tbl->set<Variant>( it->second->getName(), iRow, 0);
			tbl->set<Variant>( it->second->getProtocol(), iRow, 1);
			tbl->set<Variant>( it->second->getClassName(), iRow, 2);
			tbl->set( it->second->getURI().clone(), iRow, 3);
		 }
		this->dbs.transactionEnd();
		return request->replyResponse(WRET_OK, tbl);
	 }
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

Response* DataBaseManager::mmDoListSupportedProtocols( const Request* request ) {
	if ( request == NULL ) return NULL;

	return NULL;
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////// STATIC METHODS

WRESULT DataBaseManager::loadObjects( std::vector<ISerializable*>& objects, const string& class_name, const string& archive_name, const string& protocol )
 {
	DataBaseManager* datab = DataBaseManager::getInstance();
	if ( datab == NULL ) return WRET_ERR_INTERNAL;

	if ( !datab->dbs.exists(protocol) ) {
		SystemError::raise(datab, datab->Log, SystemError::CRITICAL, 0, "loadObjects", "FAILED: Protocol %s not found!", protocol.c_str() );
		return WRET_ERR_PARAM;
	 }

	DataBase* db = datab->dbs.find(protocol);
	if ( db == NULL ) {
		SystemError::raise(datab, datab->Log, SystemError::CRITICAL, 0, "loadObjects", "FAILED: DB of Protocol %s is NULL!", protocol.c_str() );
		return WRET_ERR_PARAM;
	 }

	return db->loadObjects( objects, class_name, archive_name );
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

WRESULT DataBaseManager::saveObjects( std::vector<ISerializable*>& objects, const string& archive_name, const string& protocol )
 {
	DataBaseManager* datab = DataBaseManager::getInstance();
	if ( datab == NULL ) return WRET_ERR_INTERNAL;

	if ( !datab->dbs.exists(protocol) ) {
		SystemError::raise(datab, datab->Log, SystemError::CRITICAL, 0, "saveObjects", "FAILED: Protocol %s not found!", protocol.c_str() );
		return WRET_ERR_PARAM;
	 }

	DataBase* db = datab->dbs.find(protocol);
	if ( db == NULL ) {
		SystemError::raise(datab, datab->Log, SystemError::CRITICAL, 0, "saveObjects", "FAILED: DB of Protocol %s is NULL!", protocol.c_str() );
		return WRET_ERR_PARAM;
	 }

	return db->saveObjects( objects, archive_name );
 }

////////////////////////////////////////////////////////////////////////////////////////////// STATIC METHODS
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

}; // namespace wosh
